﻿using System.Windows;
using MTBrainStorm.Framework.Commands.Parameters;

namespace MTBrainStorm.Framework.Commands
{
    public class InvokeCommand : EventToCommand
    {
        public IParameterConverter ParameterConverter
        {
            get { return (IParameterConverter) GetValue(ParameterConverterProperty); }
            set { SetValue(ParameterConverterProperty, value); }
        }

        public static readonly DependencyProperty ParameterConverterProperty = DependencyProperty.Register("ParameterConverter",
                                                                                          typeof(IParameterConverter),
                                                                                          typeof (InvokeCommand),
                                                                                          new FrameworkPropertyMetadata(
                                                                                              new PropertyChangedCallback
                                                                                                  (UpdateParameterConverter)));

        private static void UpdateParameterConverter(DependencyObject source, DependencyPropertyChangedEventArgs e)
        {
            ((InvokeCommand)source).ParameterConverter = (IParameterConverter)e.NewValue;
        }

        protected override void Invoke(object parameter)
        {
            if (ParameterConverter != null)
            {
                var convertedParameter = ParameterConverter.Convert(parameter, parameter.GetType());
                if (convertedParameter != null)
                    parameter = convertedParameter;
            }

            base.Invoke(parameter);
        }
    }
}
